package com.lzh.gulimall.member.interceptor;

import com.lzh.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.lzh.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * @ClassName LoginUserInterceptor
 * @Description TODO
 * @Author liuzhihui
 * @Date 2020/9/4 0:16
 * @Version 1.0
 **/
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberResponseVo> loginUser=new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 如果是微服务之间的调用无需登录
         */
        boolean match = new AntPathMatcher().match("/member/**", request.getRequestURI());
        if (match){
            return true;
        }

        //从session中获取用户信息
        MemberResponseVo memberResponseVo = (MemberResponseVo) request.getSession().getAttribute(LOGIN_USER);

        //登录了
        if (memberResponseVo!=null){
            //将用户信息放入到ThreadLocal中，方便使用
            loginUser.set(memberResponseVo);
            return true;
        }
        //没登录
        else {
            request.getSession().setAttribute("msg","请先进行登录");
            //跳转到登录页面
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }

    }
}
